package edu.jd.movieplatform.security.user.impl;

import edu.jd.movieplatform.common.Utils;
import edu.jd.movieplatform.security.user.DelUserDto;
import edu.jd.movieplatform.security.user.User;
import edu.jd.movieplatform.security.user.UserDto;
import edu.jd.movieplatform.security.user.UserService;
import edu.jd.movieplatform.security.user.dao.UserDao;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Map;

@Service //说明这是一个受spring容器管理的业务组件(Bean)
@Transactional //说明本类的所有方法都是事务性
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Override
    public Map<String, Object> getUserPage(UserDto dto) {
        //对于仅有一条语句，并且直接返回结果，可以进一步简化
        Map<String, Object> page =Utils.getPage(dto, ()->userDao.findUserListByCondition(dto));



        return page;
    }

    @Override
    public void addUser(UserDto dto) {
        User user = getUserById(dto.getCust_username());
        if(user != null){
            throw new RuntimeException("已存在相同账号的用户！");
        }
        dto.setUser_status("cust");
        dto.setPassword(DEFAULT_PASSWORD);
        userDao.insertUsertoCust(dto);
        userDao.insertUsertoCR(dto);
    }

    @Override
    public User getUserById(String cust_username) {
        User user = userDao.findUserById(cust_username);
        return user;
    }

    @Override
    public void updateUser(UserDto dto) {
        userDao.updateUser(dto);
    }

    @Override
    public void deleteUser(DelUserDto[] delUser) {
        if(delUser==null){
            throw new RuntimeException("没有获得需要删除用户的账号！");
        }
        int cnt=findFeedBackByUserIds(delUser);
        if (cnt>0){
            throw new RuntimeException("部分用户参与了其他功能");
        }
        userDao.deleteUser(delUser);
    }

    @Override
    public int findFeedBackByUserIds(DelUserDto[] delUser) {
        int cnt=userDao.findFeedBackByUserIds(delUser);
        return cnt;
    }

    @Override
    public int findFeedBackByUser(String cust_username) {
        int cnt =userDao.findFeedBackByUser(cust_username);
        return cnt;
    }

    @Override
    public void deleteOneUser(String cust_username,String user_status) {
        int count = findFeedBackByUser(cust_username);
        if (count>0){
            throw new RuntimeException("该用户参与了反馈功能，无法删除");
        }
        userDao.deleteOneUser(cust_username,user_status);

    }

}
